//
//  OAuthViewController.swift
//  Sina(微博)
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


class OAuthViewController: UIViewController {
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
        setNavBar()
        
    }
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id="+client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    }
    //创建tabBar
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "defaultAccount")
        
    }
    //tabBar的点击事件
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func defaultAccount() {
        let JSONString = "document.getElementById('userId').value = 'leiggee@126.com' ,document.getElementById('passwd').value = 'oyonomg'"
        webView.stringByEvaluatingJavaScriptFromString(JSONString)
    }
}

extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com/"){
            return true
        }
        if !urlString.hasPrefix("http://www.baidu.com"){
            return false
        }
        let query = request.URL?.query
        if let q = query {
            let codeStr = "code="
            let code = q.substringFromIndex(codeStr.endIndex)
            loadAccessToken(code)
        }
        
        
        return true
        
    }
    private func loadAccessToken(code: String) {
        
        UserAccountViewModel().LoadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                self.close()
                
                
            }else{
                print("登录失败")
            }
        }
        
        
        
    }
}















